<template>
  <el-dialog
    title="申请报名"
    :visible.sync="dialogVisible"
    width="650px"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="题目名称">
        <span>{{ currentTopic ? currentTopic.title : '' }}</span>
</el-form-item>
      
      <el-form-item label="指导教师">
        <span>{{ currentTopic ? currentTopic.teacherName : '' }}</span>
      </el-form-item>
      
      <el-form-item label="志愿优先级" prop="priority">
        <el-radio-group v-model="form.priority">
          <el-radio :label="1" :disabled="!canApplyPriority1">
            <span style="font-weight: bold;">第一志愿</span>
            <span v-if="!canApplyPriority1" style="color: #F56C6C; font-size: 12px;">
              (已有申请)
            </span>
            <span v-else style="color: #67C23A; font-size: 12px;">
              (推荐)
            </span>
          </el-radio>
          <el-radio :label="2" :disabled="!canApplyPriority2 || !hasPriority1Application">
            <span>第二志愿</span>
            <span v-if="!canApplyPriority2" style="color: #F56C6C; font-size: 12px;">
              (已有申请)
            </span>
            <span v-else-if="!hasPriority1Application" style="color: #F56C6C; font-size: 12px;">
              (请先填写第一志愿)
            </span>
          </el-radio>
        </el-radio-group>
        
        <!-- 志愿说明 - 优化提示 -->
        <div style="margin-top: 10px; padding: 10px; background-color: #f5f7fa; border-radius: 4px; font-size: 13px;">
          <div style="color: #606266; margin-bottom: 5px;">
            <i class="el-icon-info"></i>
            <strong>志愿填报规则：</strong>
          </div>
          <div style="color: #909399; line-height: 1.6;">
            1. 每个学生最多申请 <strong style="color: #F56C6C;">1个第一志愿</strong> 和 <strong style="color: #E6A23C;">1个第二志愿</strong><br/>
            2. 必须先填写第一志愿，才能填写第二志愿<br/>
            3. 志愿代表您的意愿程度，但不保证优先录取顺序<br/>
            4. 任何一位导师录取您后，另一个志愿将自动失效
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="申请理由" prop="applyReason">
        <el-input
          v-model="form.applyReason"
          type="textarea"
          :rows="5"
          placeholder="请简要说明您申请该题目的理由，如相关技术基础、兴趣方向、项目经验等（非必填，但建议填写以提高录取率）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <!-- 修改中警告提示 -->
    <el-alert
      v-if="isTopicPendingModification"
      title="注意：该题目正在被教师修改"
      type="warning"
      :closable="false"
      show-icon
      style="margin-top: 15px;"
    >
      <template slot="default">
        题目内容可能发生变更，请谨慎选择此志愿。建议等待教师修改完成并审核通过后再报名。
      </template>
    </el-alert>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitting">确认报名</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { applyForTopic, checkCanApply, listMyApplications } from "@/api/system/application";

export default {
  name: "ApplyDialog",
  data() {
    return {
      // 对话框显示
      dialogVisible: false,
      // 提交状态
      submitting: false,
      // 当前题目
      currentTopic: null,
      // 优先级可用性
      canApplyPriority1: false,
      canApplyPriority2: false,
      // 是否已有第一志愿 - 新增
      hasPriority1Application: false,
      // 表单数据
      form: {
        topicId: null,
        priority: 1,
        applyReason: ""
      },
      // 表单验证
      rules: {
        priority: [
          { required: true, message: "请选择志愿优先级", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    /** 判断题目是否处于修改审核中 */
    isTopicPendingModification() {
      if (!this.currentTopic) return false;
      return this.currentTopic.auditStatus === '修改待审核' && 
             this.currentTopic.hasPendingChanges === 1;
    }
  },
  methods: {
    /** 打开对话框 */
    open(topic) {
      this.currentTopic = topic;
      this.dialogVisible = true;
      
      // 重置表单
      this.form = {
        topicId: topic.topicId,
        priority: 1,
        applyReason: ""
      };
      
      // 检查优先级可用性和第一志愿状态
      this.checkPriorities();
      this.checkPriority1Status();
      
      // 清除验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate();
        }
      });
    },
    
    /** 检查优先级可用性 */
    checkPriorities() {
      checkCanApply(1).then(response => {
        this.canApplyPriority1 = response.data;
        // 如果第一志愿不可用，默认选择第二志愿（但要先检查是否有第一志愿）
        if (!this.canApplyPriority1 && this.canApplyPriority2 && this.hasPriority1Application) {
          this.form.priority = 2;
        }
      });
      
      checkCanApply(2).then(response => {
        this.canApplyPriority2 = response.data;
      });
    },
    
    /** 检查是否已有第一志愿申请 - 新增方法 */
    checkPriority1Status() {
      listMyApplications().then(response => {
        const applications = response.data || [];
        // 检查是否有第一志愿的有效申请（待审核或已录取）
        this.hasPriority1Application = applications.some(app => 
          app.priority === 1 && ['待审核', '已录取'].includes(app.status)
        );
        
        // 如果没有第一志愿，强制选择第一志愿
        if (!this.hasPriority1Application) {
          this.form.priority = 1;
        }
      }).catch(() => {
        // 出错时默认可以填写第一志愿
        this.hasPriority1Application = false;
      });
    },
    
    /** 取消 */
    cancel() {
      this.dialogVisible = false;
      this.reset();
    },
    
    /** 重置 */
    reset() {
      this.form = {
        topicId: null,
        priority: 1,
        applyReason: ""
      };
      this.currentTopic = null;
    },
    
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 再次检查第二志愿约束
          if (this.form.priority === 2 && !this.hasPriority1Application) {
            this.$modal.msgError("请先填写第一志愿后再填写第二志愿");
            return;
          }
          
          // 再次检查该优先级是否可用
          checkCanApply(this.form.priority).then(response => {
            if (!response.data) {
              this.$modal.msgError("该志愿优先级已有申请，请先取消后再申请");
              return;
            }
            
            // 提交申请
            this.submitting = true;
            applyForTopic(this.form).then(response => {
              this.$modal.msgSuccess("报名成功");
              this.dialogVisible = false;
              this.submitting = false;
              // 通知父组件刷新
              this.$emit('success');
            }).catch(() => {
              this.submitting = false;
            });
          });
        }
      });
    }
  }
};
</script>

<style scoped>
::v-deep .el-radio {
  margin-bottom: 10px;
  display: block;
  line-height: 24px;
}
</style>